package top.juanshen.print.driverpos;


import com.alibaba.fastjson.JSONObject;
import org.springframework.util.ClassUtils;
import top.juanshen.print.util.ReadUtil;

import java.io.IOException;
import java.util.Map;

/**
 * 打印任务
 * @author zhulinfeng
 * @时间 2016年9月23日下午12:59:57
 *
 */
public class PrintJob implements Runnable {

	/**
	 * 任务类型：0=普通订单 1=预定单 2=支付订单 3=警告单 4=test单
	 */
	private int missionType;
	
	/**
	 * 需要打印的参数--可扩展
	 */
	private Map<String, Object> param;
	
	/**
	 * 打印机逻辑名称
	 */
	private String printerName;
	
	public PrintJob(int missionType, Map<String, Object> param, String printerName) {
		this.missionType = missionType;
		this.param = param;
		this.printerName = printerName;
	}

	static final String BASEPATH = ClassUtils.getDefaultClassLoader().getResource("").getPath();

	public PrintJob(){

	}

	public int getMissionType() {
		return missionType;
	}

	public void setMissionType(int missionType) {
		this.missionType = missionType;
	}

	public Map<String, Object> getParam() {
		return param;
	}

	public void setParam(Map<String, Object> param) {
		this.param = param;
	}

	public String getPrinterName() {
		return printerName;
	}

	public void setPrinterName(String printerName) {
		this.printerName = printerName;
	}

	@Override
	public void run() {
		while(true){
			try {
				PrintJob printJob = PrintQueue.take();
				System.out.println("begin print job...");
				new DriverPos().print(jsonTemplateByMissionType(printJob.getMissionType()), JSONObject.toJSONString(printJob.getParam())
						, printJob.getPrinterName());
				System.out.println("end print job...");
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
			catch (IOException e) {
				e.printStackTrace();
			}
		}
	}


	/**
	 * 根据任务类型选择打印模板
	 * @param missionType	任务类型
	 * @return
	 * @throws IOException
	 */
	private static String jsonTemplateByMissionType(int missionType) throws IOException{
		String template = "";
		String path =  BASEPATH+"static/driverpos/";
		String pix = ".json";
		switch (missionType) {
			case 0:
				template = path + "simple" + pix;
				break;
			case 1:
				template = path + "preOrder" + pix;
				break;
			case 2:
				template = path + "pay" + pix;
				break;
			case 3:
				template = path + "warn" + pix;
				break;
			case 4:
				template = path + "test" + pix;
				break;

			default:
				template = path + "simple" + pix;
				break;
		}
		String json = readTxt(template, "utf-8");

		return json;
	}

	private static String readTxt(String filePathAndName, String encoding)
			throws IOException {
		return ReadUtil.ReadText(filePathAndName,encoding);
	}
}
